package com.solarfridge.monitor.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;
import com.solarfridge.monitor.shared.data.Fridge;

public class FridgeListBinder extends Composite {

	private static FridgeListBinderUiBinder uiBinder = GWT
			.create(FridgeListBinderUiBinder.class);

	interface FridgeListBinderUiBinder extends
			UiBinder<Widget, FridgeListBinder> {
	}

	private FridgeDetailDisplayer mDetailDisplayer;
	@UiField
	FlexTable fridgeTable;
	
	public FridgeListBinder(FridgeDetailDisplayer detailDisplayer) {
		initWidget(uiBinder.createAndBindUi(this));
		fridgeTable.setText(0, 0, "Fridge Id");
		mDetailDisplayer = detailDisplayer;
	}


	public void populateFridgeTable(Fridge[] fridges) {
		for (int i = 0; i < fridges.length; i++) {
			Anchor aId = new Anchor(fridges[i].getFridgeId());
			final Fridge currentFridge = fridges[i];
			aId.addClickHandler(
					new ClickHandler() {						
				@Override
				public void onClick(final ClickEvent event) {
					mDetailDisplayer.displayFridgeDetails(currentFridge);
				}
			});
			fridgeTable.setWidget(i + 1, 0, aId);
		}
	}
	
	public void showErrorMessage(String message) {
		Window.alert(message);
	}


	public static interface FridgeDetailDisplayer {
		public void displayFridgeDetails(final Fridge fridge);
	}


}
